#import "huanxinsixinview.h"
#import "MessageListModel.h"
#import "MessageListCell.h"
#import "ZFModalTransitionAnimator.h"
#import "YBCenterVC.h"
@interface huanxinsixinview()<JMessageDelegate>
@end
@implementation huanxinsixinview{
    UILabel *nothingLabel;
    NSDictionary *systemDic;
    JMSGConversation *conver_admin1;//官方通知
    JMSGConversation *conver_admin2;//系统通知
    JMSGConversation *conver_host;//主播对话
    JMSGConversation *_conversation_comment;
    JMSGConversation *_conversation_fans;
    JMSGConversation *_conversation_zan;
    JMSGConversation *_conversation_at;
}
-(instancetype)init{
    self = [super init];
    if (self) {
        idStrings=  [NSString string];
        _allArray = [NSMutableArray array];
        _JIMallArray = [NSMutableArray array];
        [JMessage addDelegate:self withConversation:nil];
        [self setview];
        self.view.backgroundColor = UIColor.whiteColor;
    }
    return self;
}

-(void)reloadMessageIM{
    
    [self forMessage];
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)setview{
    UIView *navtion = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _window_width,40)];
    navtion.backgroundColor = UIColor.whiteColor;
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(_window_width/2-50, 0, 100, 40)];
    label.text = YZMsg(@"消息");
    label.textColor = RGB_COLOR(@"#636465", 1);
    label.textAlignment = NSTextAlignmentCenter;
    label.font = NaviTitle_Font;
    [navtion addSubview:label];

    [self.view addSubview:navtion];
    UIButton *hulueBTN = [UIButton buttonWithType:UIButtonTypeCustom];
    hulueBTN.frame = CGRectMake(_window_width - 60, 0, 50, 40);
    hulueBTN.backgroundColor = [UIColor clearColor];
    [hulueBTN setTitle:YZMsg(@"忽略未读") forState:UIControlStateNormal];
    [hulueBTN setTitleColor:RGB_COLOR(@"#bfc0c1", 1) forState:UIControlStateNormal];
    hulueBTN.titleLabel.font = [UIFont systemFontOfSize:12];
    [hulueBTN addTarget:self action:@selector(weidu:) forControlEvents:UIControlEventTouchUpInside];
    [navtion addSubview:hulueBTN];

    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,40, _window_width,_window_height*0.4 - 40) style:UITableViewStylePlain];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = UIColor.whiteColor;
    nothingLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, _window_width, 20)];
    nothingLabel.center = self.tableView.center;
    nothingLabel.textColor = RGB_COLOR(@"#969696", 1);
    nothingLabel.font = [UIFont systemFontOfSize:13];
    nothingLabel.text = YZMsg(@"你还没有收到任何消息");
    nothingLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:nothingLabel];
    nothingLabel.hidden = YES;

}
- (void)onReceiveMessageRetractEvent:(JMSGMessageRetractEvent *)retractEvent;{
    [self forMessage];
}
-(void)onReceiveMessage:(JMSGMessage *)message error:(NSError *)error{
    [self forMessage];
}
-(void)onConversationChanged:(JMSGConversation *)conversation{
//    [self forMessage];
    //[self onSyncReloadConversationListWithConversation:conversation];
}
//离线消息
- (void)onSyncOfflineMessageConversation:(JMSGConversation *)conversation offlineMessages:(NSArray<__kindof JMSGMessage *> *)offlineMessages {
    DDLogDebug(@"Action -- onSyncOfflineMessageConversation:offlineMessages:");
    
    //[self onSyncReloadConversationListWithConversation:conversation];
}
//消息漫游
- (void)onSyncRoamingMessageConversation:(JMSGConversation *)conversation {
    DDLogDebug(@"Action -- onSyncRoamingMessageConversation:");
    
    //[self onSyncReloadConversationListWithConversation:conversation];
}

- (void)onSyncReloadConversationListWithConversation:(JMSGConversation *)conversation {
    if (!conversation) {
        return ;
    }
    BOOL isHave = NO;
    if (conversation.conversationType == kJMSGConversationTypeSingle) {
        JMSGUser *newUser = (JMSGUser *)conversation.target;
        for (int i = 0; i < _JIMallArray.count; i++) {
            JMSGConversation *oldConversation = _JIMallArray[i];
            if (oldConversation.conversationType == kJMSGConversationTypeSingle) {
                JMSGUser *oldUser = (JMSGUser *)oldConversation.target;
                if ([newUser.username isEqualToString:oldUser.username] && [newUser.appKey isEqualToString:oldUser.appKey]) {
                    [_JIMallArray replaceObjectAtIndex:i withObject:conversation];
                    isHave = YES;
                    break ;
                }
            }
        }
    }
    if (!isHave) {
        [_JIMallArray insertObject:conversation atIndex:0];
    }
    _JIMallArray = [self sortConversation:_JIMallArray];
    
    //_unreadCount = 0;
    NSString *idStrs = [NSString string];
    for (NSInteger i=0; i < [_JIMallArray count]; i++) {
        JMSGConversation *conversation = [_JIMallArray objectAtIndex:i];
        if (conversation.conversationType == kJMSGConversationTypeSingle) {
            //_unreadCount = _unreadCount + [conversation.unreadCount integerValue];
            NSString *name = [NSString stringWithFormat:@"%@",[conversation.target valueForKey:@"username"]];
            name = [name stringByReplacingOccurrencesOfString:JmessageName withString:@""];
            idStrs = [idStrs stringByAppendingFormat:@"%@,",name];
        }
    }
    if (idStrs.length > 1) {
        //去掉最后一个逗号
        idStrs = [idStrs substringToIndex:[idStrs length] - 1];
    }
    if (![idStrings containsString:_zhuboID]) {
        idStrings = [_zhuboID stringByAppendingFormat:@",%@",idStrings];
        JMSGConversation *con_host = [[JMSGConversation alloc]init];
        [_JIMallArray insertObject:con_host atIndex:0];
    }
    if (![idStrings containsString:@"dsp_admin_2"]) {
        idStrings = [@"dsp_admin_2" stringByAppendingFormat:@",%@",idStrings];
        JMSGConversation *con_admin2 = [[JMSGConversation alloc]init];
        [_JIMallArray insertObject:con_admin2 atIndex:0];
    }else {
        idStrings = [idStrings stringByReplacingOccurrencesOfString:@"dsp_admin_2," withString:@""];
        idStrings = [@"dsp_admin_2" stringByAppendingFormat:@",%@",idStrings];
        [_JIMallArray removeObject:conver_admin2];
        [_JIMallArray insertObject:conver_admin2 atIndex:0];
    }
    
    [self getUserList:idStrs];
    

}
#pragma mark --排序conversation
- (NSMutableArray *)sortConversation:(NSMutableArray *)conversationArr {
    NSSortDescriptor *firstDescriptor = [[NSSortDescriptor alloc] initWithKey:@"latestMessage.timestamp" ascending:NO];
    NSArray *sortDescriptors = [NSArray arrayWithObjects:firstDescriptor, nil];
    NSArray *sortedArray = [conversationArr sortedArrayUsingDescriptors:sortDescriptors];
    
    for (JMSGConversation *im_con in sortedArray) {
        if (im_con.conversationType == kJMSGConversationTypeSingle) {
            NSString *name = [NSString stringWithFormat:@"%@",[im_con.target valueForKey:@"username"]];
            name = [name stringByReplacingOccurrencesOfString:JmessageName withString:@""];
            if ([name isEqual:@"dsp_admin_2"]) {
                conver_admin2 = im_con;
            }
            if ([name isEqual:@"dsp_admin_1"]) {
                conver_admin1 = im_con;
            }
            if ([name isEqual:_zhuboID]) {
                conver_host = im_con;
            }
            if ([name isEqual:@"dsp_fans"]) {
                //粉丝
                _conversation_fans = im_con;
            }
            if ([name isEqual:@"dsp_like"]){
                //赞
                _conversation_zan = im_con;
            }
            if ([name isEqual:@"dsp_at"]){
                //@
                _conversation_at = im_con;
            }
            if ([name isEqual:@"dsp_comment"]){
                //评论
                _conversation_comment = im_con;
            }
        }
    }
    NSMutableArray *m_array = [NSMutableArray arrayWithArray:sortedArray];
    if (conver_host) {
        [m_array removeObject:conver_host];
        [m_array insertObject:conver_host atIndex:0];//主播对话
    }
    if (conver_admin2) {
        [m_array removeObject:conver_admin2];
        [m_array insertObject:conver_admin2 atIndex:0];  //只要系统消息
    }
    if (conver_admin1) {
        [m_array removeObject:conver_admin1];//不要官方消息
    }
    conver_admin2 = nil;
    conver_admin1 = nil;
    
    if (_conversation_fans) {
        [m_array removeObject:_conversation_fans];
    }
    if (_conversation_zan) {
        [m_array removeObject:_conversation_zan];
    }
    if (_conversation_at) {
        [m_array removeObject:_conversation_at];
    }
    if (_conversation_comment) {
        [m_array removeObject:_conversation_comment];
    }
    _conversation_fans = nil;
    _conversation_zan = nil;
    _conversation_at = nil;
    _conversation_comment = nil;
    
    return m_array;
}
-(void)forMessage{
    if ([[common letter_switch] isEqual:@"1"]) {

        [JMSGConversation allConversations:^(id resultObject, NSError *error) {
            if (error == nil) {
                self.JIMallArray = nil;
                self.JIMallArray = [NSMutableArray array];
                self.allArray = nil;
                self.allArray = [NSMutableArray array];
                self.JIMallArray = [[self sortConversation:resultObject] mutableCopy];
                //[self.tableView reloadData];
                idStrings = nil;
                idStrings = [NSString string];
                for (int i=0; i < [self.JIMallArray count]; i++) {
                    JMSGConversation *conversation = [_JIMallArray objectAtIndex:i];
                    NSString *name = [NSString stringWithFormat:@"%@",[conversation.target valueForKey:@"username"]];
                    name = [name stringByReplacingOccurrencesOfString:JmessageName withString:@""];
                    idStrings = [idStrings stringByAppendingFormat:@"%@,",name];
                    if ([name isEqual:@"dsp_admin_2"]) {
                        conver_admin2 = conversation;
                    }
                }
                if (![idStrings containsString:_zhuboID]) {
                    idStrings = [_zhuboID stringByAppendingFormat:@",%@",idStrings];
                    JMSGConversation *con_host = [[JMSGConversation alloc]init];
                    [_JIMallArray insertObject:con_host atIndex:0];
                }
                if (![idStrings containsString:@"dsp_admin_2"]) {
                    idStrings = [@"dsp_admin_2" stringByAppendingFormat:@",%@",idStrings];
                    JMSGConversation *con_admin2 = [[JMSGConversation alloc]init];
                    [_JIMallArray insertObject:con_admin2 atIndex:0];
                }else {
                    idStrings = [idStrings stringByReplacingOccurrencesOfString:@"dsp_admin_2," withString:@""];
                    idStrings = [@"dsp_admin_2" stringByAppendingFormat:@",%@",idStrings];
                    [_JIMallArray removeObject:conver_admin2];
                    [_JIMallArray insertObject:conver_admin2 atIndex:0];
                }
                //获取列表所有人的id
                if (idStrings.length > 1) {
                    //获取列表所有人的id
                    idStrings = [idStrings substringToIndex:[idStrings length] - 1];
                    [self getUserList:idStrings];
                    nothingLabel.hidden = YES;
                }else{
                    nothingLabel.hidden = NO;
                }
            }
            else{
                self.allArray = nil;
                [self.tableView reloadData];
            }
        }];
    }
}
-(void)getUserList:(NSString *)touid{
    [self.allArray removeAllObjects];;
    NSString *url = [NSString stringWithFormat:@"User.getMultiInfo&uid=%@&uids=%@",[Config getOwnID],touid];
    [WYNetworking postWithUrl:url Dic:nil Suc:^(int code, id info, NSString *msg) {
        if (code == 0) {
            NSArray *infos = info;
            for (int i=0; i<infos.count; i++) {
                NSMutableDictionary *subdic = [NSMutableDictionary dictionaryWithDictionary:infos[i]];
                NSString *utot = [NSString stringWithFormat:@"%@",[subdic valueForKey:@"utot"]];
                [self.allArray addObject:subdic];
                for (JMSGConversation *conversation in self.JIMallArray) {
                    NSString *conversationid = [NSString stringWithFormat:@"%@",[conversation.target valueForKey:@"username"]];
                    conversationid = [conversationid stringByReplacingOccurrencesOfString:JmessageName withString:@""];
                    NSString *touid = [NSString stringWithFormat:@"%@",[subdic valueForKey:@"id"]];
                    if ([conversationid isEqual:touid]) {
                        [subdic setObject:conversation forKey:@"conversation"];
                    }
                }
            }
            [self.tableView reloadData];
        }
    } Fail:^(id fail) {
        
    }];
    
}
//忽略未读
-(void)weidu:(UIButton *)sender{
    sender.enabled = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        sender.enabled = YES;
    });
    [[NSUserDefaults standardUserDefaults] setObject:minstr([systemDic valueForKey:@"addtime"]) forKey:@"notifacationOldTime"];
    [_tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    int unreadCount = 0;
    for (JMSGConversation *Conversation in self.JIMallArray) {
        unreadCount += [Conversation.unreadCount intValue];
        [Conversation clearUnreadCount];
    }
    if (unreadCount>0) {
        [self showAlert:YZMsg(@"已经忽略未读消息")];
        [self forMessage];
    }else{
        [self showAlert:YZMsg(@"当前暂无未读消息")];
    }
}

//提示框
-(void)showAlert:(NSString *)msg;{
    NSDictionary *contentDic = @{
                                @"title":@"",
                                @"msg":msg,
                                @"left":@"",
                                @"right":YZMsg(@"确定")
    };
    [YBAlertView showAlertView:contentDic complete:^(int eventType) {
        
    }];
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row>1) {
        return YES;
    }
    return NO;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        [MBProgressHUD showError:YZMsg(@"系统消息无法删除")];
        return;
    }
    MessageListModel *model = [[MessageListModel alloc] initWithDictionary:self.allArray[indexPath.row]];
    [JMSGConversation deleteSingleConversationWithUsername:[NSString stringWithFormat:@"%@%@",JmessageName,model.uidStr]];
    [self forMessage];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.allArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MessageListCell *cell = [MessageListCell cellWithTab:tableView andIndexPath:indexPath];
    cell.isWhiteStyle = YES;
    
    MessageListModel *model = [[MessageListModel alloc] initWithDictionary:self.allArray[indexPath.row]];
    cell.model = model;
    if ([model.uidStr isEqual:_zhuboID]) {
        cell.timeL.hidden = YES;
        cell.redPoint.hidden = YES;
        cell.siliaoL.hidden = NO;
        if (cell.detailL.text.length == 0 || [PublicObj checkNull:model.contentStr]) {
            cell.detailL.text = YZMsg(@"Hi～我是主播，快来和我聊天吧。");
        }else{
            cell.detailL.text = model.contentStr;
            cell.timeL.hidden = NO;
            cell.siliaoL.hidden = YES;
            int num = [model.unReadStr intValue];
            if (num > 0) {
                cell.redPoint.hidden = NO;
            }else{
                cell.redPoint.hidden = YES;
            }
        }
    }else{
        cell.timeL.hidden = NO;
        cell.siliaoL.hidden = YES;
        int num = [model.unReadStr intValue];
        if (num > 0) {
            cell.redPoint.hidden = NO;
        }else{
            cell.redPoint.hidden = YES;
        }
    }
    
    cell.iconTag.hidden = YES;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    YBWeakSelf;
    cell.iconEvent = ^(NSString *type) {
        [weakSelf goCenter:model.uidStr];
    };
    return cell;
    
}
-(void)goCenter:(NSString *)hostID{
   /* 10-26 统一直播间内的私信头像主页跳转去掉
    if ([hostID isEqual:@"dsp_admin_1"]||[hostID isEqual:@"dsp_admin_2"]) {
        return;
    }
    
    YBCenterVC *center = [[YBCenterVC alloc]init];
    center.otherUid =hostID;
    center.isPush = YES;
    center.hidesBottomBarWhenPushed = YES;
    [[YBBaseAppDelegate sharedAppDelegate] pushViewController:center animated:YES];
    */
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];

    MessageListModel *model = [[MessageListModel alloc] initWithDictionary:self.allArray[indexPath.row]];
    NSDictionary *userDic = @{
        @"id":model.uidStr,
        @"user_nickname":model.unameStr,
        @"avatar":model.iconStr,
    };
    [[YBMessageManager shareManager] chatWithUser:userDic];
}
@end
